package com.hongkuncheng.cms.controller.admin;

import java.util.*;

import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.sql.JoinType;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Subqueries;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.helper.AdminHelper;
import com.hongkuncheng.cms.helper.DataHelper;
import com.hongkuncheng.cms.helper.DateHelper;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.helper.StringHelper;
import com.hongkuncheng.cms.model.Admin;
import com.hongkuncheng.cms.model.Article;
import com.hongkuncheng.cms.model.ArticleReColumns;
import com.hongkuncheng.cms.model.ArticleState;
import com.hongkuncheng.cms.model.ChecknodeReAdmin;
import com.hongkuncheng.cms.model.Organization;
import com.hongkuncheng.cms.model.Zhuanti;
import com.hongkuncheng.cms.model.Checknode;
import com.hongkuncheng.cms.model.Checkrecord;
import com.hongkuncheng.cms.model.CheckrecordResult;
import com.hongkuncheng.cms.model.Columns;
import com.hongkuncheng.cms.controller.BaseController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 文档管理
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/article")
public class AarticleController extends BaseController {

    private Criteria getArticleCriteria(List<Criterion> criterions) {
        Criteria criteria = factorySession.createCriteria(Article.class, "this_")
                .createAlias("articleReColumnses", "arc", JoinType.LEFT_OUTER_JOIN)
                .createAlias("arc.columns", "article_columns", JoinType.LEFT_OUTER_JOIN)
                .createAlias("article_columns.zhuanti", "article_columns_zhuanti", JoinType.LEFT_OUTER_JOIN)
                .createAlias("admin", "article_admin", JoinType.LEFT_OUTER_JOIN)
                .createAlias("article_admin.department", "article_admin_department", JoinType.LEFT_OUTER_JOIN)
                .createAlias("article_admin.adminGlobalpermission",
                        "article_admin_adminGlobalpermission", JoinType.LEFT_OUTER_JOIN);
        for (Criterion criterion : criterions) criteria.add(criterion);
        return criteria;
    }

    // 文档列表
    @RequestMapping
    public String index() {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        List<Criterion> criterions = new ArrayList<Criterion>();
        StringBuilder callbackparams = new StringBuilder();
        boolean onlyme = request.getParameter("onlyme") != null;
        if (onlyme || admin.getAdminGlobalpermission().getId() == 1) {
            criterions.add(Restrictions.eq("article_admin.id", admin.getId()));
            callbackparams.append("&onlyme=1");
        } else if (admin.getAdminGlobalpermission().getId() == 2) {
            criterions.add(Restrictions.eq("article_admin_department.id", admin.getDepartment().getId()));
        }
        request.setAttribute("onlyme", onlyme);
        int stateId = request.getParameter("stateid") == null ? 4 : Integer.parseInt(request.getParameter("stateid"));
        int columnsId = request.getParameter("columnsid") == null ? -1 : Integer.parseInt(request.getParameter("columnsid"));
        int zhuantiId = request.getParameter("zhuantiid") == null ? -1 : Integer.parseInt(request.getParameter("zhuantiid"));
        if (columnsId > -1) {
            if (columnsId > 0) {
                // 内容模块
                boolean onlycurcolumns = request.getParameter("onlycurcolumns") != null;
                if (onlycurcolumns) {
                    criterions.add(Restrictions.eq("article_columns.id", columnsId));
                    callbackparams.append("&onlycurcolumns=1");
                } else
                    criterions.add(Restrictions.or(Restrictions.eq("article_columns.id", columnsId),
                            Restrictions.eq("article_columns.parentId", columnsId)));
                request.setAttribute("onlycurcolumns", onlycurcolumns);
                int childCount = Integer.parseInt(factorySession.createCriteria(Columns.class)
                        .add(Restrictions.eq("parentId", columnsId))
                        .setProjection(Projections.countDistinct("id"))
                        .uniqueResult().toString());
                request.setAttribute("onlycurcolumnsisshow", childCount > 0);
            } else {
                // 未分类
                if (stateId == 1) {
                    DetachedCriteria decriteriaArc = DetachedCriteria.forClass(ArticleReColumns.class, "arc");
                    decriteriaArc.setProjection(Projections.property("article"));
                    decriteriaArc.add(Restrictions.eqProperty("article.id", "this_.id"));
                    criterions.add(Subqueries.notExists(decriteriaArc));
                } else {
                    columnsId = -1;
                }
            }
            callbackparams.append("&columnsid=" + columnsId);
        } else if (zhuantiId > -1) {
            criterions.add(Restrictions.eq("article_columns_zhuanti.id", zhuantiId));
            callbackparams.append("&zhuantiid=" + zhuantiId);
        }
        request.setAttribute("columnsid", columnsId);
        request.setAttribute("zhuantiid", zhuantiId);
        String title = request.getParameter("title") == null ? "" : request.getParameter("title");

        if (!title.isEmpty()) {
            criterions.add(Restrictions.like("title", title, MatchMode.ANYWHERE));
            callbackparams.append("&title=" + title);
        }
        request.setAttribute("title", title);
        for (int i = 1; i < 5; i++) {
            Criteria criteArticleState = getArticleCriteria(criterions);
            request.setAttribute("state" + i, criteArticleState.add(Restrictions.eq("articleState.id", i))
                    .setProjection(Projections.count("id"))
                    .setProjection(Projections.countDistinct("id"))
                    .uniqueResult().toString());
        }
        criterions.add(Restrictions.eq("articleState.id", stateId));
        callbackparams.append("&stateid=" + stateId);
        request.setAttribute("stateid", stateId);
        String sortfield = request.getParameter("sortfield") == null ? "id" : request.getParameter("sortfield");
        String sortmethod = request.getParameter("sortmethod") == null ? "desc" : request.getParameter("sortmethod");
        callbackparams.append("&sortfield=" + sortfield);
        callbackparams.append("&sortmethod=" + sortmethod);
        request.setAttribute("sortfield", sortfield);
        request.setAttribute("sortmethod", sortmethod);
        Criteria criterTemp = getArticleCriteria(criterions);
        if (callbackparams.length() > 0) callbackparams.deleteCharAt(0);
        request.setAttribute("callbackparams", callbackparams);
        int pageIndex = request.getParameter("pageindex") == null || request.getParameter("callbackparams") != null &&
                !callbackparams.toString().equals(request.getParameter("callbackparams")) ? 1 :
                Integer.parseInt(request.getParameter("pageindex"));
        int datasize = getDataSize();
        Order order = sortmethod.equals("desc") ? Order.desc(sortfield) : Order.asc(sortfield);
        List<Integer> articleIds = criterTemp.setProjection(Projections.distinct(Projections.property("id"))).
                addOrder(order).setFirstResult((pageIndex - 1) * datasize).setMaxResults(datasize).list();
        Criteria criteriaArticle = factorySession.createCriteria(Article.class);
        List<Article> articles = new ArrayList<Article>();
        if (articleIds.size() > 0) articles = criteriaArticle.add(Restrictions.in("id", articleIds))
                .addOrder(order).list();
        request.setAttribute("articles", articles);
        request.setAttribute("pageindex", pageIndex);
        int recordcount = 0;
        if (articleIds.size() > 0) {
            Criteria criterArticlePage = getArticleCriteria(criterions);
            recordcount = Integer.parseInt(criterArticlePage.setProjection(Projections.countDistinct("id"))
                    .uniqueResult().toString());
        }
        request.setAttribute("recordcount", recordcount);
        int pagecount = DataHelper.calcPageCount(recordcount, datasize);
        request.setAttribute("pagecount", pagecount);
        // 栏目集合
        List<Columns> columnses = new ArrayList<Columns>();
        List<Columns> columnsForZhuanties = new ArrayList<Columns>();
        List<Zhuanti> zhuantis = new ArrayList<Zhuanti>();
        List<Integer> zhuantiIds = new ArrayList<Integer>();
        List<Columns> columns1es = factorySession.createCriteria(Columns.class)
                .add(Restrictions.eq("parentId", 0))
                .addOrder(Order.asc("sort")).list();
        for (Columns columns1 : columns1es) {
            List<Columns> columns2Temp = factorySession.createCriteria(Columns.class)
                    .add(Restrictions.eq("columnsType.id", 1))
                    .add(Restrictions.eq("parentId", columns1.getId()))
                    .addOrder(Order.asc("sort")).list();
            if (columns1.getColumnsType().getId() == 1 || columns2Temp.size() > 0)
                columnses.add(columns1);
            if (columns2Temp.size() > 0)
                for (Columns columns2 : columns2Temp) columnses.add(columns2);
            if (columns1.getColumnsType().getId() == 6) {
                if (!zhuantiIds.contains(columns1.getZhuanti().getId())) {
                    zhuantis.add(columns1.getZhuanti());
                    zhuantiIds.add(columns1.getZhuanti().getId());
                }
                columnsForZhuanties.add(columns1);
            }
        }
        request.setAttribute("columnses", columnses);
        request.setAttribute("zhuantis", zhuantis);
        request.setAttribute("columnsForZhuanties", columnsForZhuanties);
        List<Organization> organizations = factorySession.createCriteria(Organization.class)
                .add(Restrictions.ne("project", applicationName))
                .add(Restrictions.eq("attach", true)).addOrder(Order.asc("sort")).list();
        request.setAttribute("organizations", organizations);
        if (articleIds.size() > 0 && stateId == 3) {
            // 如果状态为待审时，检测文档是否可撤销
            Map<Integer, Boolean> cancallbackarticle = new HashMap<Integer, Boolean>();
            List<Integer> cancallbackarticleIds = new ArrayList<Integer>(); // 能否撤销的文件ID集合
            for (Article article : articles) {
                if (article.getCheckrecords().size() == 1) {
                    List<Checknode> checknodes = factorySession.createCriteria(Checknode.class)
                            .createAlias("checkflow", "checkflow", JoinType.LEFT_OUTER_JOIN)
                            .add(Restrictions.eq("checkflow.id", article.getCheckflowId()))
                            .add(Restrictions.eq("checkflow.active", true))
                            .addOrder(Order.asc("sort")).list(); // 和当前文档流程节点同属于同一（启用）流程的所有节点集合
                    if (article.getChecknode().getId() == checknodes.get(1).getId())
                        cancallbackarticleIds.add(article.getId());
                }
            }
            request.setAttribute("cancallbackarticleids", cancallbackarticleIds);
        }
        return view();
    }

    // 文档详细（只读）
    @RequestMapping("detail")
    public String detail() {
        int articleId = Integer.parseInt(request.getParameter("articleid"));
        Article article = factorySession.get(Article.class, articleId);
        if (article == null) {
            PageHelper.alertAndRedirect("文档已被其它管理人员删除", "./?stateid=1");
            return null;
        }
        List<Integer> columnsIds = new ArrayList<Integer>();
        for (ArticleReColumns arc : article.getArticleReColumnses()) columnsIds.add(arc.getColumns().getId());
        request.setAttribute("article", article);
        request.setAttribute("columnsids", columnsIds);
        // 栏目集合
        List<Columns> columnses = new ArrayList<Columns>();
        List<Columns> columnsForZhuanties = new ArrayList<Columns>();
        List<Zhuanti> zhuantis = new ArrayList<Zhuanti>();
        List<Integer> zhuantiIds = new ArrayList<Integer>();
        List<Columns> columns1es = factorySession.createCriteria(Columns.class)
                .add(Restrictions.eq("parentId", 0))
                .addOrder(Order.asc("sort")).list();
        for (Columns columns1 : columns1es) {
            List<Columns> columns2Temp = factorySession.createCriteria(Columns.class)
                    .add(Restrictions.eq("columnsType.id", 1))
                    .add(Restrictions.eq("parentId", columns1.getId()))
                    .addOrder(Order.asc("sort")).list();
            if (columns1.getColumnsType().getId() == 1 || columns2Temp.size() > 0)
                columnses.add(columns1);
            if (columns2Temp.size() > 0)
                for (Columns columns2 : columns2Temp) columnses.add(columns2);
            if (columns1.getColumnsType().getId() == 6) {
                if (!zhuantiIds.contains(columns1.getZhuanti().getId())) {
                    zhuantis.add(columns1.getZhuanti());
                    zhuantiIds.add(columns1.getZhuanti().getId());
                }
                columnsForZhuanties.add(columns1);
            }
        }
        request.setAttribute("columnses", columnses);
        request.setAttribute("zhuantis", zhuantis);
        request.setAttribute("columnsForZhuanties", columnsForZhuanties);
        return view();
    }

    // 文档编辑（可编辑）
    @RequestMapping("edit")
    public String edit() {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        int articleId = request.getParameter("articleid") == null ? 0 :
                Integer.parseInt(request.getParameter("articleid"));
        Article article = articleId == 0 ? new Article() : factorySession.get(Article.class, articleId);
        if (article == null) {
            PageHelper.alertAndRedirect("文档已被其它管理人员删除", "./?stateid=1");
            return null;
        }
        // 栏目集合
        Set<Integer> columnsIds = new HashSet<>();
        List<Columns> columnses = new ArrayList<Columns>();
        List<Columns> columnsForZhuanties = new ArrayList<Columns>();
        List<Zhuanti> zhuantis = new ArrayList<Zhuanti>();
        Set<Integer> zhuantiIds = new HashSet<>();
        List<Columns> columns1es = factorySession.createCriteria(Columns.class)
                .add(Restrictions.eq("parentId", 0))
                .addOrder(Order.asc("sort")).list();
        for (Columns columns1 : columns1es) {
            List<Columns> columns2Temp = factorySession.createCriteria(Columns.class)
                    .add(Restrictions.eq("columnsType.id", 1))
                    .add(Restrictions.eq("parentId", columns1.getId()))
                    .addOrder(Order.asc("sort")).list();
            if (columns1.getColumnsType().getId() == 1 || columns2Temp.size() > 0)
                columnses.add(columns1);
            if (columns2Temp.size() > 0)
                for (Columns columns2 : columns2Temp) columnses.add(columns2);
            if (columns1.getColumnsType().getId() == 6) {
                if (!zhuantiIds.contains(columns1.getZhuanti().getId())) {
                    zhuantis.add(columns1.getZhuanti());
                    zhuantiIds.add(columns1.getZhuanti().getId());
                }
                columnsForZhuanties.add(columns1);
            }
        }
        if (articleId == 0) {
            article.setSource("本单位");
            article.setAuthor(admin.getName());
            article.setPublishtime(new Date());
            int columnsId = request.getParameter("columnsid") == null ? -1 : Integer.parseInt(request.getParameter("columnsid"));
            if (columnsId > 0) {
                for (Columns columns : columnses) {
                    if (columns.getColumnsType().getId() == 1 && columns.getId() == columnsId) {
                        columnsIds.add(columnsId);
                        break;
                    }
                }
            }
            int zhuantiId = request.getParameter("zhuantiid") == null ? -1 : Integer.parseInt(request.getParameter("zhuantiid"));
            if (zhuantiId > 0) {
                for (Columns columnsForZhuanti : columnsForZhuanties) {
                    if (columnsForZhuanti.getColumnsType().getId() == 1 && columnsForZhuanti.getId() == columnsId) {
                        columnsIds.add(zhuantiId);
                        break;
                    }
                }
            }
        } else {
            for (ArticleReColumns arc : article.getArticleReColumnses()) columnsIds.add(arc.getColumns().getId());
        }
        request.setAttribute("article", article);
        request.setAttribute("columnsids", columnsIds);
        request.setAttribute("columnses", columnses);
        request.setAttribute("zhuantis", zhuantis);
        request.setAttribute("columnsForZhuanties", columnsForZhuanties);
        request.setAttribute("callbackparams", request.getParameter("callbackparams"));
        return view();
    }

    // 文档编辑处理
    @RequestMapping("editdo")
    @ResponseBody
    public void editdo() {
        checkAdminPermission("office_article_manage");
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        int articleId = Integer.parseInt(request.getParameter("articleid"));
        int stateId = Integer.parseInt(request.getParameter("stateid"));
        Article article = articleId == 0 ? new Article() :
                factorySession.load(Article.class, articleId, LockMode.PESSIMISTIC_WRITE);
        if (article == null) {
            PageHelper.alertAndRedirect("文档已被其它管理人员删除", "./?" + request.getParameter("callbackparams"));
            return;
        }
        article.setArticleState(factorySession.load(ArticleState.class, stateId));
        article.setTitle(request.getParameter("title"));
        article.setBold(request.getParameter("bold") != null);
        article.setRed(request.getParameter("red") != null);
        article.setDigest(request.getParameter("digest"));
        article.setExturl(request.getParameter("exturl"));
        article.setContents(StringHelper.escapeXss(request.getParameter("contents")));
        article.setContenttext(StringHelper.escapeHtml(article.getContents()));
        article.setImage(request.getParameter("image"));
        article.setSource(request.getParameter("source"));
        article.setAuthor(request.getParameter("author"));
        article.setPublishtime(DateHelper.convertToDatetime(request.getParameter("publishtime")));
        article.setClicknum(Integer.parseInt(request.getParameter("clicknum")));
        article.setSort(Integer.parseInt(request.getParameter("sort")));
        if (request.getParameter("protection") != null) {
            article.setProtection(true);
            article.setProtectionpassword(request.getParameter("protectionpassword"));
        } else {
            article.setProtection(false);
            article.setProtectionpassword(null);
        }
        List<Integer> columnsIds = DataHelper.convertToIntegerList(request.getParameterValues("columnsids"));
        if (articleId == 0) {
            article.setAdmin(admin);
            factorySession.save(article);
            recordLog("新增文档《" + article.getTitle().trim() + "》");
        } else {
            if (article.getArticleReColumnses().size() > 0) {
                // 删除原来的映射关系
                List<Object> arcs = new ArrayList<>();
                for (ArticleReColumns arc : article.getArticleReColumnses()) {
                    if (!columnsIds.contains(arc.getColumns().getId())) arcs.add(arc);
                    else columnsIds.remove(Integer.valueOf(arc.getColumns().getId()));
                }
                factorySession.delete(arcs);
            }
            recordLog("修改文档《" + article.getTitle().trim() + "》");
        }
        if (columnsIds.size() > 0) {
            // 创建新的映射关系
            List<Columns> columnses = factorySession.createCriteria(Columns.class)
                    .add(Restrictions.in("id", columnsIds))
                    .list();
            for (Columns columns : columnses) {
                ArticleReColumns arc = new ArticleReColumns();
                arc.setArticle(article);
                arc.setColumns(columns);
                factorySession.save(arc);
            }
        }
        switch (stateId) {
            case 1:
                if (articleId == 0)
                    PageHelper.confirmAndRedirect("保存成功，是否继续新建文档？", "edit", "./?" +
                            (request.getParameter("callbackparams").isEmpty() ? "stateid=1" :
                                    request.getParameter("callbackparams")));
                else
                    PageHelper.alertAndRedirect("保存成功", "./?" + request.getParameter("callbackparams"));
                break;
            case 3:
                PageHelper.alertAndRedirect("提交成功，请等待审核", "./?" +
                        request.getParameter("callbackparams").replaceAll("stateid=(\\d+)", "stateid=3"));
                break;
            case 4:
                if (admin.getId() != article.getAdmin().getId()) {
                    boolean needcheck = false;
                    for (ChecknodeReAdmin cnra : article.getAdmin().getChecknodeReAdmins()) {
                        if (cnra.getChecknode().getChecknodeType().getId() == 1) {
                            needcheck = true;
                            break;
                        }
                    }
                    if (needcheck) {
                        // 设置记录
                        Checkrecord checkrecord = new Checkrecord();
                        checkrecord.setArticle(article);
                        checkrecord.setAdmin(admin);
                        checkrecord.setCheckrecordResult(factorySession.load(CheckrecordResult.class, 4));
                        checkrecord.setSubmittime(new Date());
                        factorySession.save(checkrecord);
                    }
                }
                Criteria criterArticleState1 = factorySession.createCriteria(Article.class, "this_")
                        .createAlias("admin", "article_admin", JoinType.LEFT_OUTER_JOIN)
                        .createAlias("article_admin.department", "article_admin_department", JoinType.LEFT_OUTER_JOIN);
                if (admin.getAdminGlobalpermission().getId() == 1) {
                    criterArticleState1.add(Restrictions.eq("article_admin.id", admin.getId()));
                } else if (admin.getAdminGlobalpermission().getId() == 2) {
                    criterArticleState1.add(Restrictions.eq("article_admin_department.id", admin.getDepartment().getId()));
                }
                int state1count = Integer.parseInt(criterArticleState1.add(Restrictions.eq(
                        "articleState.id", 1)).setProjection(Projections.count("id"))
                        .setProjection(Projections.countDistinct("id")).uniqueResult().toString());
                if (state1count > 0) stateId = 1;
                recordLog("发布文档《" + article.getTitle().trim() + "》");
                admin = factorySession.get(Admin.class, admin.getId());
                if (article.getArticleState().getId() == 4 && AdminHelper.checkAdminPermission(admin, "office_create_")) {
                    PageHelper.confirmAndRedirect("发布成功，是否生成相关静态页面？",
                            "../createpage/articlerelevancefilepaths?articleids=" + article.getId(),
                            "./?" + request.getParameter("callbackparams").replaceAll("stateid=(\\d+)",
                                    "stateid=4"));
                } else {
                    PageHelper.alertAndRedirect("保存成功", "./?" + request.getParameter("callbackparams"));
                }
                break;
        }
    }

    // 从列表发布文章
    @RequestMapping("publish")
    @ResponseBody
    public void publish() {
        checkAdminPermission("office_article_manage");
        String articleids = request.getParameter("articleids");
        String[] articleIds = articleids.split(",");
        List<Article> articles = factorySession.createCriteria(Article.class)
                .add(Restrictions.in("id", DataHelper.convertToIntegerArray(articleIds)))
                .list();
        ArticleState articleState = factorySession.load(ArticleState.class, 4);
        CheckrecordResult checkrecordResult = factorySession.load(CheckrecordResult.class, 4);
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        for (Article article : articles) {
            article.setArticleState(articleState);
            article.setChecknode(null);
            if (admin.getId() != article.getAdmin().getId()) {
                boolean needcheck = false;
                for (ChecknodeReAdmin cnra : article.getAdmin().getChecknodeReAdmins()) {
                    if (cnra.getChecknode().getChecknodeType().getId() == 1) {
                        needcheck = true;
                        break;
                    }
                }
                if (needcheck) {
                    // 设置记录
                    Checkrecord checkrecord = new Checkrecord();
                    checkrecord.setArticle(article);
                    checkrecord.setAdmin(admin);
                    checkrecord.setCheckrecordResult(factorySession.load(CheckrecordResult.class, 4));
                    checkrecord.setSubmittime(new Date());
                    factorySession.save(checkrecord);
                }
            }
        }
        Criteria criterArticleState1 = factorySession.createCriteria(Article.class, "this_")
                .createAlias("admin", "article_admin", JoinType.LEFT_OUTER_JOIN)
                .createAlias("article_admin.department", "article_admin_department", JoinType.LEFT_OUTER_JOIN);
        if (admin.getAdminGlobalpermission().getId() == 1) {
            criterArticleState1.add(Restrictions.eq("article_admin.id", admin.getId()));
        } else if (admin.getAdminGlobalpermission().getId() == 2) {
            criterArticleState1.add(Restrictions.eq("article_admin_department.id", admin.getDepartment().getId()));
        }
        int state1count = Integer.parseInt(criterArticleState1
                .add(Restrictions.eq("articleState.id", 1))
                .setProjection(Projections.count("id"))
                .setProjection(Projections.countDistinct("id"))
                .uniqueResult().toString());
        int stateId = state1count > 0 ? 1 : 4;
        recordLog("发布《" + articles.get(0).getTitle().trim() + "》等" + articles.size() + "篇文档");
        admin = factorySession.get(Admin.class, admin.getId());
        if (AdminHelper.checkAdminPermission(admin, "office_create_")) {
            PageHelper.confirmAndRedirect("发布成功，是否生成相关静态页面？",
                    "../createpage/articlerelevancefilepaths?articleids=" + articleids,
                    "./?stateid=" + stateId);
        } else {
            PageHelper.alertAndRedirect("发布成功", "./?stateid=" + stateId);
        }
    }

    // 文档撤销
    @RequestMapping("callback")
    @ResponseBody
    public void callback() {
        checkAdminPermission("office_article_manage");
        int articleId = Integer.parseInt(request.getParameter("articleid"));
        Article article = factorySession.load(Article.class, articleId, LockMode.PESSIMISTIC_WRITE);
        article.setArticleState(factorySession.load(ArticleState.class, 1));
        article.setChecknode(null);
        article.setCheckflowId(null);
        List<Checkrecord> checkrecords = factorySession.createCriteria(Checkrecord.class)
                .add(Restrictions.eq("article.id", articleId)).setLockMode(LockMode.PESSIMISTIC_WRITE).list();
        for (Checkrecord checkrecord : checkrecords) factorySession.delete(checkrecord);
        recordLog("撤销文档《" + article.getTitle().trim() + "》");
        PageHelper.alertAndRedirect("撤销成功", "./?" + request.getParameter("callbackparams"));
    }

    // 文档移除
    @RequestMapping("remove")
    @ResponseBody
    public void remove() {
        checkAdminPermission("office_article_manage");
        String[] articleIds = request.getParameter("articleids").split(",");
        List<Article> articles = factorySession.createCriteria(Article.class)
                .add(Restrictions.in("id", DataHelper.convertToIntegerArray(articleIds)))
                .setLockMode(LockMode.PESSIMISTIC_WRITE).list();
        for (Article article : articles) {
            article.setArticleState(factorySession.load(ArticleState.class, 5));
            article.setRemovetime(new Date());
        }
        recordLog("移除《" + articles.get(0).getTitle().trim() + "...》等" + articles.size() + "篇文档");
        PageHelper.alertAndRedirect("移除成功", "./?" +
                request.getParameter("callbackparams").replaceAll("stateid=(\\d+)", "stateid=1"));
    }

    // 文档下架
    @RequestMapping("downshelf")
    @ResponseBody
    public void downshelf() {
        checkAdminPermission("office_article_manage");
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        String articleids = request.getParameter("articleids");
        String[] articleIds = articleids.split(",");
        List<Article> articles = factorySession.createCriteria(Article.class)
                .add(Restrictions.in("id", DataHelper.convertToIntegerArray(articleIds)))
                .setLockMode(LockMode.PESSIMISTIC_WRITE).list();
        for (Article article : articles) {
            article.setArticleState(factorySession.load(ArticleState.class, 1));
            article.setChecknode(null);
            article.setCheckflowId(null);
        }
        List<Criterion> criterions = new ArrayList<Criterion>();
        criterions.add(Restrictions.eq("articleState.id", 4));
        if (admin.getAdminGlobalpermission().getId() == 1) {
            criterions.add(Restrictions.eq("article_admin.id", admin.getId()));
        } else if (admin.getAdminGlobalpermission().getId() == 2) {
            criterions.add(Restrictions.eq("article_admin_department.id", admin.getDepartment().getId()));
        }
        Criteria criterArticleState1 = factorySession.createCriteria(Article.class, "this_")
                .createAlias("admin", "article_admin", JoinType.LEFT_OUTER_JOIN)
                .createAlias("article_admin.department", "article_admin_department", JoinType.LEFT_OUTER_JOIN);
        if (admin.getAdminGlobalpermission().getId() == 1) {
            criterArticleState1.add(Restrictions.eq("article_admin.id", admin.getId()));
        } else if (admin.getAdminGlobalpermission().getId() == 2) {
            criterArticleState1.add(Restrictions.eq("article_admin_department.id", admin.getDepartment().getId()));
        }
        int state1count = Integer.parseInt(criterArticleState1
                .add(Restrictions.eq("articleState.id", 1))
                .setProjection(Projections.count("id"))
                .setProjection(Projections.countDistinct("id"))
                .uniqueResult().toString());
        int stateId = state1count > 0 ? 1 : 4;
        recordLog("下架《" + articles.get(0).getTitle().trim() + "...》等" + articles.size() + "篇文档");
        admin = factorySession.get(Admin.class, admin.getId());
        if (AdminHelper.checkAdminPermission(admin, "office_create_")) {
            PageHelper.confirmAndRedirect("下架成功，是否生成相关静态页面？",
                    "../createpage/articlerelevancefilepaths?articleids=" + articleids,
                    "./?" + request.getParameter("callbackparams").replaceAll("stateid=(\\d+)",
                            "stateid=" + stateId));
        } else {
            PageHelper.alertAndRedirect("下架成功", "./?" +
                    request.getParameter("callbackparams").replaceAll("stateid=(\\d+)",
                            "stateid=" + stateId));
        }
    }

}
